import React, {Component} from 'react';
import {
    Addition,
    BigSpace,
    Button,
    Conversion,
    HeaderContainer,
    HeaderWrapper,
    LOGO,
    Nav,
    NavItem,
    SearchBox,
    SearchBoxWrapper,
    SearchInfoContainer,
    SearchInfoItem,
    SearchInfoList,
    SearchInfoTitle,
} from "./style";
import './style.css';
import {CSSTransition} from "react-transition-group";
import {connect} from "react-redux";
import store from "@/store";
import {actions} from './store'
import {actions as windowActions} from '@/common/window/store'
import {withRouter} from "react-router-dom";
import {errorMsg, successMsg, successTitleMsg} from "@/util/global";
import {EditOutlined, HomeOutlined, MobileOutlined, UserAddOutlined, UserOutlined} from '@ant-design/icons';
import {Affix, Avatar, Popover} from "antd";
import {getPath} from "@/util/routerUtil";
import EventBus from "@/util/EventBus";
import MinePopover from "@/common/header/MinePopover";
import {getNumber} from "@/util/Regex";
import Confirm from "@/common/Modal/Confirm";
import {clearUserInfo} from "@/util/UserUtil";
import {regainUserInfo} from "@/api/SysUserInfo";
import {toBase64} from "@/util/CodeUtils";
import {INIT_USER_INFO} from "@/store/common/user/type";


class Header extends Component {
    constructor(props) {
        super(props);
        this.PushToUploadGame = this.PushToUploadGame.bind(this);
        this.EventResolve = this.EventResolve.bind(this);
        this.PushToLogin = this.PushToLogin.bind(this);
        this.PushToMine = this.PushToMine.bind(this);
        this.PushToJoinUs = this.PushToJoinUs.bind(this);
        this.PushToHome = this.PushToHome.bind(this);
        this.LoginOut = this.LoginOut.bind(this);
        this.PushToUploadPage = this.PushToUploadPage.bind(this);
        this.handleClickSearchBtn = this.handleClickSearchBtn.bind(this);
        this.handleClickLoginOut = this.handleClickLoginOut.bind(this);
        this.props.handleChangeRouter(window.location.pathname)
        /* 路由事件监听 */
        this.props.history.listen(location => {
            this.props.handleChangeRouter(location.pathname)
        })
        // 定义全局可以访问的Router
        window._ROUTER_ = this.props.history;
        this.state = {
            loginOutVisible: false
        }
    }

    componentDidMount() {
        /* 初始化热搜数据 */
        store.dispatch(actions.headerSearchInit());
        /* 处理全局刷新用户信息事件 */
        EventBus.addListener('RegainUserInfo', async () => {
            /* 实时更新 */
            await regainUserInfo()
                .then(response => {
                    if (response.data) {
                        this.props.regainUser(response.data);
                        sessionStorage.setItem('just-game-obj', toBase64(response.data));
                    }
                })
        });
    }

    componentWillUnmount() {
        /* 移除事件监听 */
        window.removeEventListener('click', this.EventResolve);
    }

    PushToUploadGame() {
        if (this.props.userInfo.userid && this.props.userInfo.onlineId) {
            this.props.history.push('/upload-game');
        } else {
            errorMsg("请先登录再尝试！")
            this.PushToLogin();
        }
    }

    handleClickSearchBtn(e) {
        e.preventDefault();
        if (getPath() === '/search') {
            EventBus.emit('searchGames', this.props.searchValue)
        } else {
            this.props.history.push({pathname: '/search', query: {kw: this.props.searchValue}});
        }
        // 清空搜索框内容
        // this.props.handleClearInputSearch();
    }

    EventResolve(e) {
        if (!this.props.TopSearchFocused && !this.props.searchFocused) {
            this.props.handleClickTopSearchEvent(false);
            window.removeEventListener('click', this.EventResolve);
        }
    }

    addEventListen() {
        window.addEventListener('click', this.EventResolve, true)
    }

    PushToLogin() {
        this.props.history.push('/login');
    }

    PushToMine() {
        if (this.props.userInfo.userid && this.props.userInfo.onlineId) {
            this.props.history.push('/mine/info');
        } else {
            errorMsg("请先登录再尝试！")
            this.PushToLogin();
        }
    }

    PushToUploadPage() {
        this.props.history.push('/page');
    }

    PushToJoinUs() {
        this.props.history.push('/login/sign');
    }

    PushToHome() {
        this.props.history.push('/home')
    }

    handleClickLoginOut(bool) {
        this.setState({logoutVisible: bool})
    }


    LoginOut() {
        clearUserInfo();
        this.props.handleChangeRouter('/home');
        window._ROUTER_.push("/home");
        this.handleClickLoginOut(false);
    }

    render() {
        /* 隐藏Header */
        if (!this.props.visible){
            return null;
        }
        const addEventListen = this.addEventListen.bind(this)
        const {
            shouldTopSearchOpen,
            handleTopSearchFocus,
            handleClickConversion,
            TopSearchWords,
            searchFocused,
            handleSearchFocusEvent,
            searchValue,
            userInfo,
            handleInputSearchInfo
        } = this.props

        return (
            <>
                {/* 退出登录前弹出弹窗询问操作 */}
                <Confirm content={"您确定要退出登陆吗？"} titleText={"温馨提示"}
                         visible={this.state.logoutVisible} onOk={this.LoginOut}
                         onCancel={() => this.handleClickLoginOut(false)}/>
                <HeaderWrapper id={"Header"}   style={{width: this.props.width}}
                               headerNeedFixed={this.props.headerNeedFixed}
                               isScrollToTop={this.props.isScrollToTop}
                >
                    <HeaderContainer>
                        <LOGO onClick={() => this.PushToHome()}/>
                        <Addition>
                            <NavItem className='uploadPage'>
                                <EditOutlined style={{marginRight: '10px'}}/>
                                <span onClick={() => this.PushToUploadPage()}>发布资讯</span>
                            </NavItem>
                        </Addition>
                        <Nav>
                            <NavItem className='left active' onClick={this.PushToHome}>
                                <HomeOutlined style={{marginRight: '5px'}}/>首页
                            </NavItem>
                            {
                                getNumber(this.props.width) > 960 ?
                                    <NavItem className='left' onClick={()=>successTitleMsg("","敬请期待！")}>
                                        <MobileOutlined style={{marginRight: '5px'}}/>
                                        下载APP
                                    </NavItem> : null
                            }
                            <SearchBoxWrapper>
                                <CSSTransition
                                    timeout={1000 * 0.3}
                                    in={!!searchFocused}
                                    classNames="slide"
                                >
                                    <SearchBox
                                        headerNeedFixed={this.props.headerNeedFixed}
                                        onChange={(e) => handleInputSearchInfo(e)}
                                        value={searchValue}
                                        onKeyDown={(e) => {
                                            if (e.key === 'Enter') {
                                                this.handleClickSearchBtn(e)
                                            }
                                        }}
                                        onFocus={() => {
                                            handleSearchFocusEvent(true);
                                            addEventListen();
                                        }}
                                        onBlur={(e) => {
                                            handleSearchFocusEvent(false)
                                        }}

                                        className={searchFocused ? 'search-focus' : ''}/>
                                </CSSTransition>
                                <i className={searchFocused ? 'search-focus iconfont zoom' : 'iconfont zoom'}
                                   style={{color:this.props.headerNeedFixed?'rgba(0,0,0,0)':'rgba(0,0,0,1)'}}
                                   onMouseDown={this.handleClickSearchBtn}>&#xe605;</i>
                                <SearchInfoContainer className={shouldTopSearchOpen ? 'display' : 'hidden'}
                                                     onMouseEnter={() => handleTopSearchFocus(true)}
                                                     onMouseLeave={() => handleTopSearchFocus(false)}>
                                    <SearchInfoTitle>
                                        热搜
                                        <Conversion onClick={(e) => handleClickConversion(e.target)}>
                                            <span style={{float: 'right'}}>换一批</span>
                                            <i id="HeaderSwitch" className='iconfont spin'>&#xe629;</i>
                                        </Conversion>
                                    </SearchInfoTitle>
                                    <SearchInfoList>
                                        {
                                            TopSearchWords.map((item, index) => {
                                                return (
                                                    <SearchInfoItem key={index}>{item}</SearchInfoItem>
                                                )
                                            })
                                        }
                                    </SearchInfoList>
                                </SearchInfoContainer>
                            </SearchBoxWrapper>
                            {
                                /* 通过判断是否登陆来决定展示什么样的导航栏 */
                                userInfo.userid
                                    ?
                                    <NavItem className='mine'>
                                        {/* 用户登录后将鼠标放置在用户的名字上时会显示更多细节 */}
                                        <Popover content={<MinePopover userInfo={this.props.userInfo} that={this}/>}
                                                 overlayStyle={{position: "fixed"}}
                                                 destroyTooltipOnHide={true}
                                                 placement={"bottom"}
                                        >
                                            <Avatar
                                                onClick={this.PushToMine}
                                                style={{userSelect: "none"}}
                                                src={userInfo.images}>
                                                {userInfo.onlineName}
                                            </Avatar>
                                        </Popover>
                                    </NavItem>
                                    :
                                    <>

                                        <NavItem className='right'>
                                            <UserOutlined style={{marginRight: '5px'}}/>
                                            <a onClick={() => this.PushToLogin()}>登录</a>
                                            <label>/</label>
                                            <a onClick={() => this.PushToJoinUs()}>注册</a>
                                        </NavItem>
                                    </>

                            }
                            {/*{*/}
                            {/*    getNumber(this.props.width) > 1020 ?*/}
                            {/*        <NavItem className='right'>*/}
                            {/*            <i className='iconfont'>&#xe602;</i>*/}
                            {/*        </NavItem>*/}
                            {/*        :*/}
                            {/*        null*/}
                            {/*}*/}
                        </Nav>
                    </HeaderContainer>
                </HeaderWrapper>
                <BigSpace/>
            </>
        )
    }
}

const mapStateToProps = (state) => {
    return {
        /*引入redux-immutable后写法*/
        width: state.getIn(['window', 'width']),
        visible: state.getIn(['header', 'visible']),
        searchValue: state.getIn(['header', 'searchValue']),
        searchFocused: state.getIn(['header', 'searchFocused']),
        TopSearchWords: state.getIn(['header', 'TopSearchWords']),
        TopSearchFocused: state.getIn(['header', 'TopSearchFocused']),
        shouldTopSearchOpen: state.getIn(['header', 'shouldTopSearchOpen']),
        isScrollToTop: state.getIn(['window', 'isScrollToTop']),
        headerNeedFixed: state.getIn(['window','headerNeedFixed']),
        userInfo: state.getIn(['user']).toJS(),
    }
};

const mapDispatchToProps = (dispatch) => {
    return {
        handleClickConversion(e) {
            let DOM = document.getElementById('HeaderSwitch');
            let originAngle = DOM.style.transform.replace(/[^0-9]/ig, '');
            if (originAngle) {
                originAngle = parseInt(originAngle, 10);
            } else {
                originAngle = 0;
            }
            DOM.style.transform = 'rotate( ' + (originAngle + 360) + 'deg )';
        },
        handleSearchFocusEvent(bool) {
            dispatch(actions.headerSearchFocused(bool));
            // if (bool)
            //     dispatch(actions.headerTopSearchOpen(true));
        },
        handleClearInputSearch() {
            dispatch(actions.headerSearchInput(''))
        },
        handleInputSearchInfo(e) {
            dispatch(actions.headerSearchInput(e.target.value))
        },
        handleTopSearchFocus(bool) {
            dispatch(actions.headerTopSearchFocused(bool))
        },
        handleClickTopSearchEvent(bool) {
            // dispatch(actions.headerTopSearchOpen(bool));
        },
        handleChangeRouter(val) {
            dispatch(windowActions.setWindowRouter(val));
        },
        regainUser(data) {
            let action = {
                type: INIT_USER_INFO,
                value: data
            };
            dispatch(action);
        }
    }

}
export default connect(mapStateToProps, mapDispatchToProps)(withRouter(Header));
